<?php

namespace yak\layui\widgets\form;

use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;
use yii\widgets\InputWidget;

/**
 * Class IconPicker
 * @package yak\layui\widgets\form
 */
class UploadWell extends InputWidget
{
    /**
     * @var string
     */
    public $type = 'drag'; // 0 渲染 1 click

    /**
     * @var
     */
    public $url = ['upload'];

    public function run()
    {
        $id = $this->getId();
        $url = Url::toRoute($this->url);
        echo Html::activeHiddenInput($this->model, $this->attribute, ['id' => $id . '-upload-input']);
        return call_user_func_array([$this, 'render' . ucfirst($this->type)], [$id, $url]);
    }

    public function renderDrag($id, $url)
    {
        $js = <<<JS
        //拖拽上传
          layui.use(['upload'], function () {
              var upload = layui.upload
              upload.render({
                elem: '#{$id}'
                , url: '{$url}'
                , done: function(res){
                    if (res.status === 200) {
                        layer.msg('上传成功');
                        layui.$('#{$id}-upload-view').removeClass('layui-hide').find('img').attr('src', res.src);
                        layui.$('#$id-upload-input').val(res.src)
                    } else {
                        layer.alert(res.msg)
                    }
                }
              });
          })
JS;
        $this->getView()->registerJs($js, View::POS_END);

        $value = $this->model[$this->attribute];

        return '<div class="layui-upload-drag" id="' . $id . '">
            <i class="layui-icon"></i>
            <p>点击上传，或将文件拖拽到此处</p>
            <div class="' . ($value?'':'layui-hide') . '" id="' . $id . '-upload-view">
                <hr>
                <img src="' . $value . '" alt="上传成功后渲染" style="max-width: 196px">
            </div>
        </div>';
    }
}